<?php

namespace App\Http\Controllers;

use App\Models\Bankcard;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class BankcardController extends Controller
{
    public function add(Request $request)
    {
        $exists = Bankcard::where('number', $request->bankcard)->exists();
        if ($exists) {
            fail('银行卡已绑定');
        }

        $user = auth()->user();


        $count = $user->bankcards()->count();
        $user->bankcards()->create([
            'bank' => $request->bank,
            'number' => $request->bankcard,
            'default' => $count === 0
        ]);
        return success('ok');
    }

    public function addNew(Request $request)
    {
        $exists = Bankcard::where('number', $request->bankcard)->exists();
        if ($exists) {
            fail('银行卡已绑定');
        }
        $user = auth()->user();
        $user->realname = $request->realname;
        $user->save();

        $count = $user->bankcards()->count();
        $user->bankcards()->create([
            'bank' => $request->bank,
            'number' => $request->bankcard,
            'default' => $count === 0
        ]);
        return success('ok');
    }

    public function destroy($id)
    {
        $bankcard = Bankcard::findOrFail($id);
        if ($bankcard->user_id !== auth()->id()) {
            forbidden();
        }
        $bankcard->delete();
        return success('ok');
    }
}
